<link rel="import" href="../../bower_components/polymer/polymer-element.html">
<link rel="import" href="../../bower_components/vaadin-material-theme/vaadin-combo-box.html">
<link rel="import" href="../view-app.html">
<link rel="import" href="../style/shared-styles.html">
<dom-module id="view-setup-machine">
    <template>
        <style include="shared-styles app-grid-style flat-button">
            :host {
                display: block;
                margin: 10px;
                --app-grid-item-height: 50%;
            }

            .btn {
                margin: 15px 10px 0 0;
                width: 250px;
            }

            .btn-block {
                width: 100%;
            }

            .machine {
                margin: 10px;
                padding: 20px;
                border: 1px solid rgba(0, 0, 0, .10);
                border-radius: 5px;
            }

            .machine p {
                margin: 10px 0;
            }

            .machine h1 {
                text-align: center;
            }

            .search-input {
                margin: 0 10px;
            }
        </style>
        <firebase-auth app-name="smart-mes" id="auth" user="{{user}}"></firebase-auth>
        <firebase-document app-name="smart-mes" id="userData" path="/user/[[user.uid]]" data="{{k}}"></firebase-document>
        <firebase-query app-name="smart-mes" id="machineQuery" path="/data/[[k.key]]/factoryData/machine" data="{{machineItems}}"></firebase-query>
        <firebase-document app-name="smart-mes" id="editMachineQuery" path="/data/[[k.key]]/factoryData/machine/[[editKey]]" data="{{editMachineItems}}"></firebase-document>
        <app-localstorage-document key="app-lang" data="{{language}}"></app-localstorage-document>
        <!-- Add Machine Card -->
        <div class="card main-card" hidden="[[showAddMachine]]">
            <h1 class="title">{{localize('add-machine')}}</h1>
            <paper-input type="number" id="machineNumber" label="{{localize('machine-number')}}" value="[[getMachineNumber(machineItems.length)]]"
                min="1" max="999" readonly required always-float-label></paper-input>
            <paper-input type="text" id="machineName" label="Machine Name" required error-message="Invalid Input" always-float-label></paper-input>
            <paper-input type="number" id="machineCapacity" label="{{localize('machine-max-capacity')}} (items/hour)" min="1" max="9999"
                step="1" allowed-pattern="^(0|[1-9]\d*)$" required always-float-label></paper-input>
            <vaadin-combo-box id="machineType" label="{{localize('machine-type')}}" items="[[machineType]]" item-value-path="name" item-label-path="name"
                loading="[[!machineType]]" allow-custom-value always-float-label required>
                <template>
                    <paper-item>
                        <paper-item-body two-line style="min-height: 0">
                            <div style="text-transform: capitalize">[[item.name]]</div>
                            <div secondary>Code: [[item.code]]</div>
                        </paper-item-body>
                    </paper-item>
                </template>
            </vaadin-combo-box>
            *For custom machine type just type custom name in this input field.
            <div class="center">
                <flat-button class="btn" on-click="openMachineListCard">
                    <button>{{localize('dismiss')}}</button>
                </flat-button>
                <flat-button class="btn shamrock" on-click="addMachine">
                    <button disabled="[[disabled]]">{{localize('add')}}</button>
                </flat-button>
            </div>
        </div>
        <!-- Edit Machine Card -->
        <div class="card main-card" hidden="[[showEditMachine]]">
            <h1 class="title">{{localize('edit-machine')}}</h1>
            <paper-input type="number" id="edit_machineNumber" label="{{localize('machine-number')}}" value="[[editMachineItems.number]]"
                min="1" max="999" readonly required always-float-label></paper-input>
            <paper-input type="text" id="edit_machineName" label="Machine Name" value="[[editMachineItems.name]]" required error-message="Invalid Input"
                always-float-label></paper-input>
            <paper-input type="number" id="edit_machineCapacity" label="{{localize('machine-max-capacity')}} ({{localize('items')}}/{{localize('hour')}})"
                min="1" max="9999" step="1" value="[[editMachineItems.capacity]]" required always-float-label></paper-input>
            <vaadin-combo-box id="edit_machineType" label="{{localize('machine-type')}}" value="[[editMachineItems.type]]" items="[[machineType]]"
                item-value-path="name" item-label-path="name" loading="[[!machineType]]" allow-custom-value always-float-label required>
                <template>
                    <paper-item>
                        <paper-item-body two-line style="min-height: 0">
                            <div style="text-transform: capitalize">[[item.name]]</div>
                            <div secondary>Code: [[item.code]]</div>
                        </paper-item-body>
                    </paper-item>
                </template>
            </vaadin-combo-box>
            <div class="center">
                <flat-button class="btn" on-click="openMachineListCard">
                    <button>{{localize('dismiss')}}</button>
                </flat-button>
                <flat-button class="btn shamrock" on-click="saveMachine">
                    <button>{{localize('save')}}</button>
                </flat-button>
            </div>
        </div>
        <!-- Machine Management -->
        <div class="card main-card" hidden="[[showListMachine]]">
            <h1 class="title">{{localize('machine-management')}}</h1>
            <paper-input class="search-input" label="搜索机床名称" id="searchMachineInput" value="{{searchString::input}}" type="text"
                always-float-label hidden="[[!machineItems]]"></paper-input>
            <h1 class="sub-title center" hidden="[[machineItems]]">{{localize('please-add-machine-before-adding-station')}}</h1>
            <ul class="app-grid">
                <template is="dom-repeat" filter="{{searchMachine(searchString)}}" items="{{machineItems}}" observe="name" index-as="name"
                    as="machineItem">
                    <li>
                        <div class="machine">
                            <div class="machine-info-group">
                                <h2 class="title">[[machineItem.name]]</h2>
                                <p>{{localize('machine-number')}}: [[machineItem.number]]</p>
                                <p>{{localize('machine-type')}}: [[machineItem.type]]</p>
                                <p>{{localize('machine-max-capacity')}}: [[machineItem.capacity]] {{localize('items')}}/ {{localize('hour')}}</p>
                                <p>{{localize('machine-install-date')}}: [[getInstallDate(machineItem.install)]]</p>
                            </div>
                            <flat-button class="btn btn-block" on-click="openEditMachineCard" machine="[[machineItem]]">
                                <button>{{localize('edit')}}</button>
                            </flat-button>
                            <flat-button class="btn btn-block thunderbird " on-click="removeMachine" machine="[[machineItem]]">
                                <button>{{localize('remove')}}</button>
                            </flat-button>
                        </div>
                    </li>
                </template>
            </ul>
            <div class="center">
                <paper-button class="btn" on-click="openAddMachineCard">{{localize('add-machine')}}</paper-button>
            </div>
        </div>
        <paper-toast id="toastAlert" always-on-top horizontal-align="right" text="{{localize(toastText)}}"></paper-toast>
    </template>
    <script>
        /**
         * @ViewSetupMachine
         * @polymer 
         * @extends {Polymer.Element}
         */
        class ViewSetupMachine extends Polymer.mixinBehaviors([Polymer.AppLocalizeBehavior], Polymer.Element) {
            static get is() {
                return 'view-setup-machine'
            }

            static get properties() {
                return {
                    language: String,
                    toastText: String,
                    editKey: String,
                    machineItems: {
                        type: Object,
                        notify: true
                    },
                    editMachineItems: Object,
                    showAddMachine: {
                        type: Boolean,
                        value: true
                    },
                    showEditMachine: {
                        type: Boolean,
                        value: true
                    },
                    showListMachine: {
                        type: Boolean,
                        value: false
                    },
                    disabled: {
                        type: Boolean,
                        value: true
                    },
                    machineType: {
                        type: Array,
                        value: () => {
                            return [
                            {
                                "name": "Baking",
                                "code": "bake"
                            },
                            {
                                "name": "Boiling",
                                "code": "boil"
                            },
                            {
                                "name": "Compressing",
                                "code": "comp"
                            },
                            {
                                "name": "Cutting",
                                "code": "cut"
                            },
                            {
                                "name": "Coating",
                                "code": "coat"
                            },
                            {
                                "name": "Chemical reaction",
                                "code": "react"
                            },
                            {
                                "name": "Freezing",
                                "code": "freeze"
                            },
                            {
                                "name": "Folding",
                                "code": "fold"
                            },
                            {
                                "name": "Gluing",
                                "code": "glue"
                            },
                            {
                                "name": "Drilling",
                                "code": "drill"
                            },                            
                            {
                                "name": "Labeling",
                                "code": "lab"
                            },
                            {
                                "name": "Lathing",
                                "code": "lathe"
                            },
                            {
                                "name": "Painting",
                                "code": "paint"
                            },
                            {
                                "name": "Printing",
                                "code": "print"
                            },
                            {
                                "name": "Packing",
                                "code": "pack"
                            },
                            {
                                "name": "Rolling",
                                "code": "roll"
                            },
                            {
                                "name": "Slotting",
                                "code": "slot"
                            },
                            {
                                "name": "Stitching",
                                "code": "stich"
                            },
                            {
                                "name": "Squeezing",
                                "code": "sque"
                            },
                            {
                                "name": "Streaming",
                                "code": "stream"
                            },
                            {
                                "name": "Stretching",
                                "code": "stretch"
                            },
                            {
                                "name": "Washing",
                                "code": "wash"
                            },
                            {
                                "name": "Welding",
                                "code": "welding"
                            },
                            {
                                "name": "CNC",
                                "code": "cnc"
                            },
                            {
                                "name": "TRN",
                                "code": "trn"
                            },
                            {
                                "name": "ASS",
                                "code": "ass"
                            },
                            {
                                "name": "C&P",
                                "code": "c&p"
                            },
                            {
                                "name": "Other",
                                "code": "oth"
                            },
                            ]
                        }
                    }
                }
            }

            connectedCallback() {
                super.connectedCallback()
                this.loadResources(this.resolveUrl('../../data/locales.json'))
            }

            ready() {
                super.ready()
                requestAnimationFrame(this._installListeners.bind(this))
            }

            searchMachine(keyword) {
                if (!keyword) {
                    // set filter to null to disable filtering
                    return null;
                } else {
                    // return a filter function for the current search keyword
                    keyword = keyword.toLowerCase()
                    return ((machine) => {
                        let name = machine.name.toLowerCase()
                        return (name.indexOf(keyword) != -1)
                    });
                }
            }

            _installListeners() {
                this.$.machineNumber.addEventListener('input', this._validateInput.bind(this))
                this.$.machineName.addEventListener('input', this._validateInput.bind(this))
                this.$.machineType.addEventListener('value-changed', this._validateInput.bind(this))
                this.$.machineCapacity.addEventListener('input', this._validateInput.bind(this))
            }

            _validateInput() {
                const number = this.$.machineNumber.value
                const name = this.$.machineName.value
                const type = this.$.machineType.value
                const capacity = this.$.machineCapacity.value
                if (number && name && type && capacity >= 0 && capacity <= 9999) {
                    this.disabled = false
                } else {
                    this.disabled = true
                }
            }

            getInstallDate(timestamp) {
                const today = new Date(timestamp * 1000)
                let dd = today.getDate()
                let mm = today.getMonth() + 1 //January is 0!
                let yyyy = today.getFullYear()
                if (dd < 10) {
                    dd = '0' + dd
                }
                if (mm < 10) {
                    mm = '0' + mm
                }
                const deliveryDate = dd + '/' + mm + '/' + yyyy
                return deliveryDate
            }

            getMachineNumber(length) {
                if (length > 0) {
                    return length + 1
                } else {
                    return 1
                }
            }

            openAddMachineCard() {
                this.showAddMachine = false
                this.showListMachine = true
            }

            openEditMachineCard(e) {
                this.showEditMachine = false
                this.showListMachine = true
                let key = e.currentTarget.machine.$key
                this.editKey = key
            }

            openMachineListCard() {
                this.showEditMachine = true
                this.showAddMachine = true
                this.showListMachine = false
                this._clearField()
            }

            addMachine() {
                const number = this.$.machineNumber.value
                const name = this.$.machineName.value
                const capacity = this.$.machineCapacity.value
                const type = this.$.machineType.value
                const code = this.$.machineType.value.substring(0, 3).toLowerCase();
                const timestamp = Math.round(Date.now() / 1000.0)
                if (number && name && capacity && type && code && timestamp) {
                    this.$.machineQuery.ref.push({
                        number: number,
                        name: name,
                        capacity: capacity,
                        type: type,
                        code: code,
                        install: timestamp
                    })
                    this._clearField()
                    this.toastText = 'notification-add-machine-successfully'
                    this.$.toastAlert.open()
                    this.openMachineListCard()
                } else {
                    this.toastText = 'notification-error-incomplete-input'
                    this.$.toastAlert.open()
                }
            }

            removeMachine(e) {
                if (window.confirm("Delete this machine ?") == true) {
                    let key = e.currentTarget.machine.$key
                    this.$.machineQuery.ref.child(key).remove()
                    this.toastText = 'notification-delete-machine-successfully'
                    this.$.toastAlert.open()
                }
            }

            saveMachine() {
                const name = this.$.edit_machineName.value
                const capacity = this.$.edit_machineCapacity.value
                const type = this.$.edit_machineType.value
                const code = this.$.edit_machineType.value.substring(0, 3).toLowerCase();

                if (name && capacity && type && code) {
                    this.$.editMachineQuery.ref.update({
                        name: name,
                        capacity: capacity,
                        type: type,
                        code: code,
                    })
                    this.toastText = 'notification-save-machine-successfully'
                    this.$.toastAlert.open()
                    this.openMachineListCard()
                } else {
                    this.toastText = 'notification-empty-add-machine'
                    this.$.toastAlert.open()
                }
            }

            _clearField() {
                this.$.machineNumber.value = this.machineItems.length + 1
                this.$.machineCapacity.value = ""
                this.$.machineName.value = ""
                this.$.machineType.value = ""
                this.editKey = ""
            }
        }
        customElements.define(ViewSetupMachine.is, ViewSetupMachine)
    </script>
</dom-module>